<?php

/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2019/12/5
 * Time: 14:06
 */

namespace App\Http\Controllers\LibApi;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

/**
 * 渝中区图书馆
 */
class YzqLibApiController
{
    //  private static $appId ='btkk_bxdd_yz'; //测试环境
    // private static $appSecret ='BiQ7aqYfuQ';//测试环境

    private static $appId = 'btkk_bxdd_yz'; //正式环境  与测试环境一致
    private static $appSecret = 'BiQ7aqYfuQ'; //正式环境

    private static $grantType = 'client_credentials'; //测试环境
    private static $scope = 'read';


    // '01131000000001';//测试地址  测试读者证号
    // '123456';//测试地址  测试读者证号密码

    // '01079900001111';//正式地址  测试读者证号
    //  '19870319';//正式地址  测试读者证号密码

    // private static $adminName = 'btkj_bxdd_yz';//测试地址  操作管理员账号
    // private static $password = 'btkjyz123';//测试地址  操作管理员密码

    private static $adminName = 'btkj_bxdd_yz'; //正式地址  操作管理员账号 与测试环境一致
    private static $password = '1234qwer'; //正式地址  操作管理员密码


    //上云后地址
    private static $serviceAddr = 'http://113.207.106.168:18089'; //上云后正式服务器外网地址

    private static $getToken = '/indiglibCloudApi/oauth/token'; //鉴权，获取access_token
    private static $login = '/indiglibCloudApi/api/v1/reader/login'; //front-读者登录-根据证号和密码-校验读者证号密码是否匹配并返回读者基本信息-需授权
    private static $idCardlogin = '/indiglibCloudApi/api/v1/reader/loginByIdnoAndPassword'; //front-读者登录-根据身份证和密码-返回读者列表-需授权
    private static $getReaderInfo = '/indiglibCloudApi/api/v1/reader/getReaderInfoByCardnoWithBorrowInfoAndFinInfo'; //2.17查询读者(基本信息+借阅信息+财经信息)-根据读者证号-需授权


    /**
     * 获取  access_token （已对接）
     */
    public function getAccessToken()
    {
        $url = self::$serviceAddr . self::$getToken;
        $access_token_param = array(
            "grant_type"   => self::$grantType,
            'client_id'    => self::$appId,
            'client_secret' => self::$appSecret,
            'scope'        => self::$scope,
        );

        $access_token_param = http_build_query($access_token_param);
        $result = $this->RequestCurl($url . '?' . $access_token_param, $access_token_param); //必须post请求，但是参数需要像get那样拼接
        $results = json_decode($result, true); //json字符串转为数组

        if (isset($results['error'])) exit(json_encode(['code' => 202, 'msg' => 'access_token获取失败-W']));

        $access_token = $results['access_token'];
        $expires_in = $results['expires_in'];
        //储存access_token
        Cache::put("yzq_lib_api_access_token", $access_token, $expires_in); //缓存3600秒
        return $access_token;
    }

    /**
     * 登录接口   （已对接）
     *
     * 读者证状态
     * status
     * n    读者证状态为有效
        y    读者证状态为验证
        l     读者证状态为挂失
        d    读者证状态为注销
        其他或空    读者证状态异常
     *
     * 一共5个对象  新书目 必传 marcInfo  ，已有书目，添加馆藏不用传，其余 4 个对象 都是必传
     * @param $account  读者证号
     * @param $password   密码
     * @param $type  1 为读者证号  2 身份证号码     默认读者证
     */
    public function login($account, $password, $type = 1)
    {
        // if(isCreditNo($account)){
        if ($type != 1) {
            //判断是否是身份证号登录
            return $this->idCardlogin($account, $password);
        }

        $access_token = Cache::get('yzq_lib_api_access_token');
        if (empty($access_token)) {
            $access_token =  $this->getAccessToken();
        }

        $url = self::$serviceAddr . self::$login;
        $param = [
            'cardno'  =>  $account,
            'password'  =>  md5($password),
        ];

        $param = json_encode($param);
        $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true);
        $results = json_decode($result, true); //json字符串转为数组

        if ((isset($results['error']) && $results['error'] == 'invalid_token') || $results['code'] === 401) {
            $access_token =  $this->getAccessToken();
            $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true); //然后重新请求
            $results = json_decode($result, true); //json字符串转为数组
        }

        //写入日志
        Log::channel('libapi')->info('重庆渝中区图书馆');
        Log::channel('libapi')->info('URL：' . $url . '?' . json_encode(json_decode($param, true), JSON_UNESCAPED_UNICODE));
        //写入日志
        Log::channel('libapi')->info($results);

        if (empty($results)) {
            exit(json_encode(['code' => 202, 'msg' => '接口异常,请联系管理员-W'])); //文华接口异常，直接报结果
        }

        if ($results['code'] === 1) {
            if ($results['objectData']['status'] == 'n') {
                return ['code' => 200, 'msg' => '登录成功', 'content' => $results['objectData']];
            } elseif ($results['objectData']['status'] == 'l') {
                $msg = '登录失败，该读者证挂失中';
            } elseif ($results['objectData']['status'] == 'd') {
                $msg = '登录失败，该读者证已注销';
            } else {
                $msg = '登录失败，该读者证状态异常';
            }
            return ['code' => 202, 'msg' => $msg];
        }
        return ['code' => 202, 'msg' => '登录失败,读者证号或密码不正确'];
    }

    /**
     * 登录接口（已对接）身份证号登录
     * @param $account  读者证号
     * @param $password   密码
     */
    public function idCardlogin($id_card, $password)
    {
        $account_info = $this->getReaderListByIdCard($id_card, $password);
        if ($account_info['code'] == 200) {
            //登录成功，获取读者信息
            $user_info = $this->getReaderInfo($account_info['content'][0]['cardno']);
            if ($user_info['code'] == 200) {
                return ['code' => 200, 'msg' => '登录成功', 'content' => $user_info['content']['reader']];
            } else {
                return ['code' => 202, 'msg' => '获取用户信息失败'];
            }
        }
        return ['code' => 202, 'msg' => '登录失败,读者证号或密码不正确'];
    }

   

    /**
     * 读者登录-根据身份证和密码-返回读者列表-需授权  (已对接)
     * @param $id_card  读者证号
     * @param $password   密码
     */
    public function getReaderListByIdCard($id_card, $password)
    {
        $access_token = Cache::get('yzq_lib_api_access_token');
        if (empty($access_token)) {
            $access_token =  $this->getAccessToken();
        }

        $url = self::$serviceAddr . self::$idCardlogin;
        $param = [
            'idno'  =>  $id_card,
            'password'  =>  md5($password),
        ];

        $param = json_encode($param);
        $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true);
        $results = json_decode($result, true); //json字符串转为数组
        if ((isset($results['error']) && $results['error'] == 'invalid_token') || $results['code'] === 401) {
            $access_token =  $this->getAccessToken();
            $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true); //然后重新请求
            $results = json_decode($result, true); //json字符串转为数组
        }

        //写入日志
        Log::channel('libapi')->info('重庆渝中区图书馆');
        Log::channel('libapi')->info('URL：' . $url . '?' . json_encode(json_decode($param, true), JSON_UNESCAPED_UNICODE));
        //写入日志
        Log::channel('libapi')->info($results);

        if ($results['code'] === 1) {
            return ['code' => 200, 'msg' => '获取成功', 'content' => $results['objectData']];
        }
        return ['code' => 202, 'msg' => '获取失败'];
    }

    /**
     * 查询读者(基本信息+借阅信息+财经信息)-根据读者证号-需授权   （已对接）
     * @param $cardno  读者证号
     *
     *  "readerBorrowInfo": {                   //  字段 ： eCardType ， 云服务不为空的就是云服务一卡通，云服务为空的就是本地非一卡通。
            "ableBorrowNum": 10,                //“本地非一卡通” 书还能借多少本      数量独立计算
            "cloudAbleBorrowNum": 9,            //“云服务一卡通” 书还能借多少       数量独立计算
            "ableBorrowNumNote": "本(10)云(9)",   //可借数和已借数，分为“本地非一卡通”书还能借多少，“云服务一卡通”书还能借多少
            "currentBorrowNum": 0,               //“本地非一卡通” 书已借多少本      数量独立计算
            "cloudCurrentBorrowNum": 1,          //“云服务一卡通” 书已借多少       数量独立计算
            "currentBorrowNumNote": "本(0)云(1)",
            "reservationNum": 0
        },
     */
    public function getReaderInfo($account)
    {
        $access_token = Cache::get('yzq_lib_api_access_token');
        if (empty($access_token)) {
            $access_token =  $this->getAccessToken();
        }

        $url = self::$serviceAddr . self::$getReaderInfo;
        $param = [
            'cardno'  =>  $account,
        ];

        $param = json_encode($param);
        $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true);
        $results = json_decode($result, true); //json字符串转为数组
        //  dump($results);die;
        if ((isset($results['error']) && $results['error'] == 'invalid_token') || $results['code'] === 401) {
            $access_token =  $this->getAccessToken();
            //  cache("yzq_lib_api_access_token" , $access_token , 7200);//缓存7200秒,覆盖掉之前的token
            $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true); //然后重新请求
            $results = json_decode($result, true); //json字符串转为数组
        }

        //写入日志
        Log::channel('libapi')->info('重庆渝中区图书馆');
        Log::channel('libapi')->info('URL：' . $url . '?' . json_encode(json_decode($param, true), JSON_UNESCAPED_UNICODE));
        //写入日志
        Log::channel('libapi')->info($results);


        if ($results['code'] === 1) {
            return ['code' => 200, 'msg' => '获取成功', 'content' => $results['objectData']];
        }
        return ['code' => 202, 'msg' => '读者财经信息获取失败'];
    }


    /**
     * @param $url
     * @param null $params
     * @param bool $json  json  格式数据    Content-Type  需要修改  成 application/json
     * @return mixed
     */
    private  static  function RequestCurl($url, $params = null, $json = false)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        if (!empty($params)) {
            if (is_array($params)) {
                //如果传的是数组，就要进行对参数进行 &拼接
                $params = http_build_query($params);
            }
            if ($json) {
                curl_setopt(
                    $ch,
                    CURLOPT_HTTPHEADER,
                    array(
                        'Content-Type: application/json',
                        'Content-Length: ' . strlen($params)
                    )
                );
            }
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        }

        $body = curl_exec($ch);
        curl_close($ch);
        return $body;
    }
}
